/**
 * @description 1. file转base64
 * @param file
 */
export const getBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    let fileResult = "";
    reader.readAsDataURL(file);
    // 开始转
    reader.onload = () => {
      fileResult = reader.result;
    };
    // 转 失败
    reader.onerror = error => {
      reject(error);
    };
    // 转 结束
    reader.onloadend = () => {
      // this.formJar.fileName = file.name
      resolve(fileResult);
    };
  });
};
/**
 * @description 2. base64转blob
 * @param base64Data
 * @param fileType
 * @returns
 */
export const base64toBlob = (base64Data, fileType = "image/png") => {
  //console.log(base64Data);//data:image/png;base64,
  let data = base64Data.startsWith("data:")
    ? base64Data
    : `data:${fileType};base64,${base64Data}`;
  var byteString;
  if (data.split(",")[0].indexOf("base64") >= 0)
    byteString = atob(data.split(",")[1]);
  //base64 解码
  else {
    byteString = unescape(data.split(",")[1]);
  }
  var mimeString = data.split(",")[0].split(":")[1].split(";")[0]; //mime类型 -- image/png
  var ia = new Uint8Array(byteString.length); //创建视图
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  var blob = new Blob([ia], {
    type: mimeString
  });
  return blob;
};

/**
 * @description 3. blob转base64
 * @param blob
 * @param callback
 */
export const blobToDataURI = (blob, callback) => {
  var reader = new FileReader();
  reader.readAsDataURL(blob);
  reader.onload = function (e) {
    callback(e.target.result);
  };
};

/**
 * @desc 4. blob转换为url
 * @param blob
 * @returns
 */
export const blobToUrl = blob => {
  return URL.createObjectURL(blob);
};

/**
 * @description 5. blob地址 to 下载
 * @param url
 * @param name
 */
export const urlDownload = function (url, name) {
  var a = document.createElement("a");
  // console.log(url)
  a.setAttribute("href", url);
  a.setAttribute("download", name);
  a.setAttribute("target", "_blank");
  let clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
};

/**
 * @description 6. file to 下载
 * @param file
 * @param name
 */
export const fileDownload = async function (file, name) {
  let getBase64Res = await getBase64(file);
  let base64toBlobRes = base64toBlob(getBase64Res);
  let blobToUrlRes = blobToUrl(base64toBlobRes);
  var a = document.createElement("a");
  a.setAttribute("href", blobToUrlRes);
  a.setAttribute("download", name);
  a.setAttribute("target", "_blank");
  let clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
};

/**
 * @description 7. base64 to 下载
 * @param base64File
 * @param name
 */
export const base64FileDownload = async function (base64File, name) {
  // let getBase64Res = await getBase64(file)
  let base64toBlobRes = base64toBlob(base64File);
  let blobToUrlRes = blobToUrl(base64toBlobRes);
  var a = document.createElement("a");
  a.setAttribute("href", blobToUrlRes);
  a.setAttribute("download", name);
  a.setAttribute("target", "_blank");
  let clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
};

/**
 * @description 8. file to url
 * @param file
 * @returns
 */
export const fileToUrl = async function (file) {
  let getBase64Res = await getBase64(file);
  let base64toBlobRes = base64toBlob(getBase64Res);
  let blobToUrlRes = blobToUrl(base64toBlobRes);
  return blobToUrlRes;
};
/**
 * @description 9. url to file
 * @param url
 * @returns
 */
export const urlToBlob = async url => {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };
    xhr.send();
  });
};

/**
 * @description 10. 获取远程地址
 * @param url
 * @returns
 */
export const getFileUrl = url => {
  // console.log(url)
  return url;
  // if (url.length && url.includes('.com/')) {
  //     return `/ossfile/${url.split('.com/')[1]}`
  // } else {
  //     return url
  // }
};

/**
 * @description 11. 判断文件的数据类型
 * audio/mpeg
 * image/jpeg
 */
export const checkFileType = file => {
  if (file.type.startsWith("image/")) {
    //图片文件
    return "image";
  } else if (file.type.startsWith("audio/")) {
    //音频文件
    return "audio";
  } else if (file.type.startsWith("video/")) {
    //视频文件
    return "video";
  } else if (file.type.startsWith("text/")) {
    //文本文件
    return "text";
  } else if (file.type.startsWith("application/")) {
    //二进制文件
    if (file.type === "application/pdf") {
      return "pdf";
    }
    if (
      file.type === "application/vnd.ms-excel" ||
      file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    ) {
      return "xls";
    }
    return "application";
  } else {
    //未知文件
    return "unknown";
  }
};

/**
 *@description 12. 图片压缩
 */
import { compress } from "image-conversion";
//把图片文件作为参数传递到方法中
export const beforeAvatarUpload = (
  file,
  isImageSizeLimit = true,
  quality = 0.4
) => {
  return new Promise((resolve, reject) => {
    // 图片小于50k不进行压缩
    const isFile50k = file.size <= 50 * 1024;
    if (isFile50k) {
      resolve(file);
      return false;
    }
    // 图片大于2mb不进行压缩
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M && isImageSizeLimit) {
      reject({
        msg: "上传头像图片大小不能超过 2MB!",
        code: 10001
      });
      return false;
    }
    compress(file, quality).then(async res => {
      let files = new File([res], file.name, {
        type: file.type,
        lastModified: Date.now()
      });
      resolve(files);
    });
  });
};

/**
 * @description 13. 从 canvas 提取图片 image
 * @param canvas
 * @returns
 */
export const convertCanvasToImage = canvas => {
  //新Image对象，可以理解为DOM
  var image = new Image();
  // canvas.toDataURL 返回的是一串Base64编码的URL
  // 指定格式 PNG
  image.src = canvas.toDataURL("image/png");
  return image;
};
/**
 * @description base64转换unicode
 * @param str
 * @returns
 */
export const b64EncodeUnicode = str => {
  return btoa(encodeURIComponent(str));
};

/**
 * @description 获取图片尺寸
 * @param url 图片链接
 * @returns
 */
export async function getImageDimension(url) {
  async function getSize(url) {
    return new Promise(res => {
      const image = new Image();
      image.src = url;
      let width = 0;
      let height = 0;
      image.onload = () => {
        width = image.width;
        height = image.height;
        res({
          width,
          height
        });
      };
    });
  }
  let res: any = await getSize(url);
  return {
    width: res.width,
    height: res.height
  };
}

/**
 * @description base64转图片
 */
export const base64ToUrl = base64File => {
  const blob = base64toBlob(base64File);
  const url = blobToUrl(blob);
  return url;
};
